package com.shire.shire_interface.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.shire.shire_interface.common.utils.JsonFormat;
import com.shire.shire_interface.common.utils.MathUtils;
import com.shire.shire_interface.common.utils.StrUtils;
import com.shire.shire_interface.conf.InstanceManager;
import com.shire.shire_interface.constants.Constants;
import com.shire.shire_interface.constants.DeviceCode;
import com.shire.shire_interface.constants.WxConstants;
import com.shire.shire_interface.constants.WxErrorCode;
import com.shire.shire_interface.controller.BaseController;
import com.shire.shire_interface.controller.kf.WebSocketController;
import com.shire.shire_interface.dao.accounts.UserAccountDao;
import com.shire.shire_interface.model.account.DeviceInfo;
import com.shire.shire_interface.model.account.WxStation;
import com.shire.shire_interface.model.accounts.UserAccount;
import com.shire.shire_interface.model.accounts.UserAccountExample;
import com.shire.shire_interface.model.clientversion.ClientVersion;
import com.shire.shire_interface.model.user.WxAccount;
import com.shire.shire_interface.service.account.WxAccountService;
import com.shire.shire_interface.service.clientversion.ClientVersionService;
import com.shire.shire_interface.service.commandcenter.BaseCommandProcessor;
import com.shire.shire_interface.service.commandcenter.WxCommandService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;


//@Api(value = "消息接口",tags = "微信端接口")
@RestController
@RequestMapping("/we")
public class ApiAccountController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(ApiAccountController.class);

    @Autowired
    private WxAccountService accountService;

    @Autowired
    private WxCommandService commandService;

    @Autowired
    private BaseCommandProcessor commandProcessor;
    @Autowired
    private ClientVersionService clientVersionService;

    @Autowired
    private UserAccountDao userAccountDao;
//    @Autowired
//    private WxStationService stationService;

//    @Autowired
//    private DeviceInfoService deviceInfoService;

    @RequestMapping("/receiveProfile.wx")
    public Map<String, Object> receiveProfile(HttpServletRequest request, @RequestBody(required=false) String body) {
        logger.info("-------------收到个人信息更新：{}", body);
        Map<String, Object> respMap = JsonFormat.toMap(body);
        String wxId = (String)respMap.get("wxId");
        WxAccount wxAccount = accountService.getWxAccountByWxId(wxId);
        if (wxAccount == null && respMap.containsKey("alias")){
            wxAccount = accountService.getWxAccountByWxId((String) respMap.get("alias"));
            if (wxAccount!=null) {
                UserAccountExample example = new UserAccountExample();
                example.createCriteria().andWxAccountEqualTo((String) respMap.get("alias"));
                List<UserAccount> userAccounts = userAccountDao.selectByExample(example);
                for (UserAccount ua : userAccounts){
                    ua.setWxAccount((String)respMap.get("wxId"));
                    userAccountDao.updateByPrimaryKey(ua);
                }
            }
        }

        if(StrUtils.isNotBlank(wxId)){
            if(wxAccount==null){
                return responseFailure("需要设定帐号");
            }

            try{
                String nick = (String)respMap.get("nick");
                String avatar = (String)respMap.get("avatar");
                String area = (String)respMap.get("area");
                String qrcode = (String)respMap.get("qrcode");
                String alias = (String)respMap.get("alias");
                if(StrUtils.isNotBlank(wxId)){
                    wxAccount.setWxid(wxId);
                }
                if(StrUtils.isNotBlank(avatar)){
                    wxAccount.setAvatar(avatar);
                }
                if(StrUtils.isNotBlank(nick)){
                    wxAccount.setNick(nick);
                }
                if(StrUtils.isNotBlank(area)){
                    wxAccount.setArea(area);
                }
                if(StrUtils.isNotBlank(alias)){
                    wxAccount.setAlias(alias);
                }
                if(StrUtils.isNotBlank(qrcode)){
                    // 写入文件
                    wxAccount.setQrcode(qrcode);
                }
                wxAccount.setInitstatus(Constants.YesNo.YES.getCode());
                wxAccount.setGender(StrUtils.getIntValue(String.valueOf(respMap.get("sex")), -1));
                wxAccount.setSignature((String)respMap.get("signature"));
                wxAccount.setAccountstatus(WxConstants.AccountStatus.ENABLE.getCode());
            }catch (Exception e){}
            if (wxAccount.getId() != null)
                accountService.updateWxAccount(wxAccount);
            else {
                wxAccount.setLogintime(new Date());
                accountService.insertWxAccount(wxAccount);
                commandProcessor.addAccount(wxAccount);
                commandProcessor.addCommand(wxAccount.getCsid(), wxAccount.getId(), commandService.genSyncAddressCmd(wxAccount));
            }

            String k = getK(request);
            String n = getN(request);
            WxStation station = InstanceManager.getInstance().getStationService().getStationByNK(n,k);
            if (station == null){
                station = new WxStation();
                station.setRealudid(getK(request));
                station.setStationno(getN(request));
                station.setWxaccountid(wxAccount.getId());
                InstanceManager.getInstance().getStationService().insertWxStation(station);
            }else {
                station.setWxaccountid(wxAccount.getId());
                InstanceManager.getInstance().getStationService().updateWxStation(station);
            }


            return responseSuccess();
        }


        return responseFailure(WxErrorCode.ACCOUNT_NOT_EXISTS, "账号信息不存在！请重新登录");
    }


    @RequestMapping("/reportAccountStatus.wx")
    public Map<String, Object> reportAccountStatus(HttpServletRequest request, @RequestBody(required=false) String body) {
        Map<String, Object> respMap = JsonFormat.toMap(body);
        WxStation station = getCurrentStation(request);
        if (station == null){
            return responseFailure("设备不存在");
        }
        WxAccount wxAccount = accountService.getWxAccountById(station.getWxaccountid());


        if (wxAccount != null) {
            Map<String, Object> reqMap = JsonFormat.toMap(body);
            Integer accountStatus = MathUtils.getMapIntValue(reqMap, "accountStatus", -1);
            if (accountStatus < 0) {
                return responseFailure("accountStatus值错误, accountStatus=" + String.valueOf(reqMap.get("accountStatus")));
            }
            if ((wxAccount.getAccountstatus() != 0 && accountStatus == 0)
                    || (wxAccount.getAccountstatus() == 0 && accountStatus > 0)) {
                wxAccount.setAccountstatus(accountStatus);
                wxAccount.setUpdatetime(new Date());
                accountService.updateWxAccount(wxAccount);
            }
            return responseSuccess();
        }
        return responseFailure("账号不存在");
    }

    /**
     * 获取station参数
     * @param request
     * @return
     */
    @RequestMapping("/reqStation.wx")
    public Map<String, Object> requestStation(HttpServletRequest request, @RequestBody(required = false)String body) {
        String k = getK(request);
        String n = getN(request);
        DeviceInfo deviceInfo = InstanceManager.getInstance().getDeviceInfoService().getDeviceInfoByUuid(k);
        if(StrUtils.isBlank(deviceInfo.getDevicemodel())){
            return responseFailure("未获得真实手机型号名称");
        }
        WxStation wxStation = InstanceManager.getInstance().getStationService().getStationByNK(n,k);
        if(wxStation==null){
            wxStation = InstanceManager.getInstance().getStationService().genNewStation(deviceInfo, n,  "北京");
        }
        if(wxStation!=null){
            if(StrUtils.isNotBlank(body)){
                wxStation.setAppjson(body);
                InstanceManager.getInstance().getStationService().updateWxStation(wxStation);
            }

            if(StrUtils.isBlank(wxStation.getParajson())){
                DeviceCode deviceCode =  InstanceManager.getInstance().getStationService().genDeviceCode(deviceInfo, "北京");
                wxStation.setParajson(JsonFormat.toJson(deviceCode));
                InstanceManager.getInstance().getStationService().updateWxStation(wxStation);
            }

            Map<String, Object> rstMap = responseSuccess();
            Map<String, Object> map = JsonFormat.toMap(wxStation.getParajson());
            rstMap.put("data", map);
            return rstMap;
        }
        return responseFailure(WxErrorCode.SYS_ERROR,"未知错误[k="+k+", n="+n+"]！");
    }

    /**
     * crk心跳
     * @param request
     * @return
     */
    @RequestMapping("/hb.de")
    public Map<String, Object> heartbeat(HttpServletRequest request, @RequestBody(required = false) String body) {
        WxStation station = getCurrentStation(request);
        if (station == null){
            return responseFailure("设备信息不存在");
        }
        WxAccount wxAccount = accountService.getWxAccountById(station.getWxaccountid());
        if (wxAccount == null){
            return responseFailure("帐号未接入");
        }
        try{
            if (wxAccount.getAccountstatus() == null && wxAccount.getAccountstatus() !=0 ){
                return responseSuccess("帐号未在线！");
            }

            //如果没有指令处理就加上
            commandProcessor.addAccount(wxAccount);

            logger.debug("hb[{}], body = {}, content-encoding={}", wxAccount.getWxid(), body, request.getHeader("content-encoding"));
            body = StrUtils.getNullStr(body, "{}");
            Map<String, Object> map = JsonFormat.toMap(body);
            String currentN = (String)map.get("currentN");
            Long currentCmdId = StrUtils.getLongValue(String.valueOf(map.get("currentCmdId")), -1);
//            if(wxAccount.getCsid()==null) return responseSuccess();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("account", wxAccount.getWxid());
            jsonObject.put("onlineTime", System.currentTimeMillis()/1000);
            jsonObject.put("opType", 4);
            List<UserAccount> list = accountService.getSystemUserByWxid(wxAccount.getWxid());
            for(UserAccount account : list) {
                WebSocketController.sendMessage(""+account.getUserId(), jsonObject.toJSONString());
            }

            wxAccount.setLogintime(new Date());
            accountService.updateWxAccount(wxAccount);
        }
        catch (Exception e){
            logger.error("心跳处理异常[k="+getK(request)+"]：", e);
        }
        return responseSuccess();
    }

    @RequestMapping("/receiveActive.de")
    public Map<String, Object> receiveActive(HttpServletRequest request, @RequestBody(required = false) String body) {
        String k = getK(request);
        try{
            logger.debug("ACTIVE[{}], body = {}", k, body);
            body = StrUtils.getNullStr(body, "{}");
            Map<String, Object> map = JsonFormat.toMap(body);
            String currentN = (String)map.get("currentN");
//            cmdProcessService.setCurrent(k, currentN, null);
//            WxStation wxStation = wxStationService.getStationByCache(k, currentN);
//            if(wxStation!=null){
//                wxStationService.updateActiveTime(wxStation.getId(), new Date());
//            }
        }
        catch (Exception e){
            logger.error("处理收到激活微信异常：", e);
        }
        return responseSuccess();
    }

    @RequestMapping(value = "/versionupdate.de", produces = "text/html; charset=utf-8")
    public String versionupdate(HttpServletRequest request) {
        logger.debug("升级地址请求：k={}, url={}?{}", getK(request), request.getRequestURI(), request.getQueryString());
        int version = getIntValue(request, "ver", -1);
        if(version<=0){
            logger.warn("未取得当前版本号，退出！！！！");
            return "ver error!!";
        }
//        String ip = getIp(request);
        ClientVersion clientVersion = clientVersionService.getValidVersion();
        if(clientVersion==null){
            return "none newVersion";
        }
        if(clientVersion.getVersion()!=null && clientVersion.getVersion()>version){
            String url = "http://w1.vcomic.com:8080/" + clientVersion.getFilepath();
            logger.info("k={}, oldVersion={}, newVersion={}, 请求升级：{}", getK(request), version, clientVersion.getVersion(), url);
            return url;
        }
        return "none";
    }

    @RequestMapping(value = "/reqDeviceGroup.de")
    public Map<String, Object> reqDeviceGroup(HttpServletRequest request) {
        String k = getK(request);
        DeviceInfo deviceInfo = InstanceManager.getInstance().getDeviceInfoService().getDeviceInfoByUuid(k);
        if(deviceInfo==null){
            return responseFailure("设备不存在！");
        }
        Map<String, Object> rstMap = responseSuccess();
        Integer groupId = MathUtils.getNullValue(deviceInfo.getGroupid(), 0);
        String groupName = "";
//        if(groupId>0) {
//            DeviceGroup deviceGroup = deviceInfoService.getDeviceGroup(deviceInfo.getGroupId());
//            if(deviceGroup!=null){
//                groupName = StrUtils.getNullStr(deviceGroup.getName());
//            }
//        }
        rstMap.put("groupId", deviceInfo.getGroupid());
        rstMap.put("groupName", groupName);
        rstMap.put("deviceNo", deviceInfo.getDeviceno());
        return rstMap;
    }

    @RequestMapping(value = "/setDeviceGroup.de")
    public Map<String, Object> setDeviceGroup(HttpServletRequest request, @RequestParam(value = "groupId") Integer groupId, @RequestParam(value = "deviceNo") String deviceNo) {
//        String k = getK(request);
//        DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByUuid(k);
//        if(deviceInfo==null){
//            return responseFailure("设备不存在！");
//        }
//        if(MathUtils.getNullValue(groupId, 0)<1 || StrUtils.isBlank(deviceNo)){
//            return responseFailure("参数错误，groupId="+groupId+", deviceNo="+deviceNo);
//        }
//        DeviceGroup deviceGroup = deviceInfoService.getDeviceGroup(groupId);
//        if(deviceGroup==null){
//            return responseFailure("设备组不存在");
//        }
//        deviceInfo.setGroupid(groupId);
//        deviceInfo.setDeviceNo(deviceNo);
//        deviceInfoService.updateDeviceInfo(deviceInfo);
        return responseSuccess();
    }

    @RequestMapping(value = "/setManualMode.de")
    public Map<String, Object> setManualMode(HttpServletRequest request) {
        String k = getK(request);
        DeviceInfo deviceInfo = InstanceManager.getInstance().getDeviceInfoService().getDeviceInfoByUuid(k);
        deviceInfo.setStatus(Constants.DeviceStatus.MANUAL.getCode());
        InstanceManager.getInstance().getDeviceInfoService().updateDeviceInfo(deviceInfo);
        return responseSuccess();
    }

    @RequestMapping(value = "/setAutoMode.de")
    public Map<String, Object> setAutoMode(HttpServletRequest request) {
        String k = getK(request);
        DeviceInfo deviceInfo = InstanceManager.getInstance().getDeviceInfoService().getDeviceInfoByUuid(k);
        deviceInfo.setStatus(Constants.DeviceStatus.ENABLE.getCode());
        InstanceManager.getInstance().getDeviceInfoService().updateDeviceInfo(deviceInfo);
        return responseSuccess();
    }
}
